package com.okhttp.get;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * @author: ywy
 * @date: 2022-11-13
 * @desc:
 */
public class ClientGet {
    static OkHttpClient client = new OkHttpClient();

    public static void getPure() {
        Request request = new Request.Builder()
                .url("http://www.baidu.com")
                .build();
        try {
            Response response = client.newCall(request).execute();
            System.out.println("[headers]" + response.headers());
            System.out.println("[status code]" + response.code());
            System.out.println("[body]" + Objects.requireNonNull(response.body()).string());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void getWithHeaders() {
        Request request = new Request.Builder()
                .url("http://localhost:8080")
                .header("Env", "dev")
                .build();
        try {
            Response response = client.newCall(request).execute();
            System.out.println("[headers]" + response.headers());
            System.out.println("[status code]" + response.code());
            System.out.println("[body]" + Objects.requireNonNull(response.body()).string());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void getWithQueryParams() {
        HttpUrl.Builder queryUrlBuilder = HttpUrl.get("http://localhost:8080/search").newBuilder();
        queryUrlBuilder.addQueryParameter("kw", "okhttp");
        Request request = new Request.Builder()
                .url(queryUrlBuilder.build())
                .get()
                .build();
        try {
            Response response = client.newCall(request).execute();
            System.out.println("[headers]" + response.headers());
            System.out.println("[status code]" + response.code());
            System.out.println("[body]" + Objects.requireNonNull(response.body()).string());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        getPure();
        System.out.println("=============");
        getWithHeaders();
        System.out.println("=============");
        getWithQueryParams();
    }
}
